package com.spring.mvc.http.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class CerRSA {
	
	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static void main(String[] args) throws CertificateException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, KeyStoreException, IOException, UnrecoverableKeyException {
		//用证书公钥加密数据
		byte[] msg="hello world!".getBytes();
		CertificateFactory factory=CertificateFactory.getInstance("X.509");
		FileInputStream fis=new FileInputStream("E:\\tianyi\\Project\\SpringMVC\\WebRoot\\ocx\\liujian.cer");
		Certificate cf=factory.generateCertificate(fis);
		fis.close();
		PublicKey publicKey=cf.getPublicKey();
		System.out.println(publicKey);
		Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] msg1=cipher.doFinal(msg);
		System.out.println("加密后的数据");
		StringBuilder sb=new StringBuilder();
		for (int i = 0; i < msg1.length; i++) {
			sb.append(hexChar[(msg1[i]&0xf0)>>4]);
			sb.append(hexChar[msg1[i]&0x0f]);
		}
		System.out.println(sb.toString().toUpperCase());
		
		//用密钥库中私钥解密数据
		FileInputStream in=new FileInputStream("E:\\tianyi\\Project\\SpringMVC\\WebRoot\\ocx\\.keystore");
		KeyStore ks=KeyStore.getInstance("JKS");
		char[] kspwd="liujian".toCharArray();
		ks.load(in,kspwd);
		PrivateKey privateKey=(PrivateKey)ks.getKey("liujian", kspwd);
		in.close();
		Cipher ciph=Cipher.getInstance("RSA/ECB/PKCS1Padding");
		ciph.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] msg2=ciph.doFinal(msg1);
		System.out.println("解密后的数据");
		System.out.println(new String(msg2));
	}
}
